﻿using System;
using Newtonsoft.Json.Linq;
using TrinityAPI.Base;
using TrinityAPI.Base.Tools;
using JingDong.Open.Platform.Tools;

namespace JingDong.Open.Platform
{
    public class GetSign : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            var header = dataset.GetJsonObject("header");
            var headerCollection = new System.Collections.Specialized.NameValueCollection();
            if (header != null)
            {
                foreach (var item in header)
                {
                    string value = header.GetJsonObjectStringValue(item.Key);
                    if (string.IsNullOrEmpty(value))
                        headerCollection.Add(item.Key, string.Empty);
                    else
                        headerCollection.Add(item.Key, value);
                }
            }
            var query = dataset.GetJsonObject("query");
            var queryCollection = new System.Collections.Specialized.NameValueCollection();
            if (query != null)
            {
                foreach (var item in query)
                {
                    string value = query.GetJsonObjectStringValue(item.Key);
                    if (string.IsNullOrEmpty(value))
                        queryCollection.Add(item.Key, string.Empty);
                    else
                        queryCollection.Add(item.Key, value);
                }
            }

            string appkey = null;
            string secret = null;
            var constant = dataset.GetJsonObject("constant");
            var signCheckConfig = constant.GetJsonObject("signCheckConfig");
            string appKeyPath = signCheckConfig.GetJsonObjectStringValue("appKeyPath");
            var accounts = signCheckConfig.GetJsonObject("accounts");
            if (!string.IsNullOrEmpty(appKeyPath))
            {
                var appkeyValue = Utils.GetValueByPath(appKeyPath, dataset);
                if (appkeyValue != null && appkeyValue.Type == JTokenType.String)
                    appkey = appkeyValue.ToString();
            }
            if (!string.IsNullOrEmpty(appkey) && accounts != null)
            {
                secret = accounts.GetJsonObject(appkey).GetJsonObjectStringValue("secret");
            }

            var request = dataset.GetJsonObject("request");
            var requestString = dataset.GetJsonObjectStringValue("requestString");

            string sign = SpiUtils.GetSign(headerCollection, queryCollection, request, requestString, secret);

            return sign;
        }
    }
}
